package cn.itsource.controller;

import cn.itsource.doc.CourseDoc;
import cn.itsource.dto.CourseQueryDto;
import cn.itsource.repo.CourseElasticsearchRepository;
import cn.itsource.result.JSONResult;
import cn.itsource.result.PageList;
import cn.itsource.service.EsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>描述</p>
 *
 * @author 波波老师(微信 ： javabobo0513)
 * @date 2022/11/15-10:40
 */
@RequestMapping("/es")
@RestController
public class EsController {

    @Autowired
    private CourseElasticsearchRepository repo;
    @Autowired
    private EsService esService;
    //前端查询
    @PostMapping("/searchCourse")
    public JSONResult searchCourse(@RequestBody CourseQueryDto courseQueryDto){
        PageList pageList = esService.searchCourse(courseQueryDto);
        return JSONResult.success(pageList);
    }

    //单个保存课程信息到ES中
    @PostMapping("/saveCourse")
    public JSONResult saveCourse2Es(@RequestBody CourseDoc doc){
        //将数据存入ES中
        repo.save(doc);
        return JSONResult.success();
    }

    //批量保存课程信息到ES中
    @PostMapping("/saveBatchCourse2Es")
    @PreAuthorize("hasAuthority('course:online')")
    public JSONResult saveBatchCourse2Es(@RequestBody List<CourseDoc> docList){
        //将数据存入ES中
        repo.saveAll(docList);
        return JSONResult.success();
    }
    //批量从ES中删除课程数据
    @PostMapping("/deleteBatchCourseFromEs")
    public JSONResult deleteBatchCourseFromEs(@RequestBody List<CourseDoc> docIds){
        //将数据存入ES中
        repo.deleteAll(docIds);
        return JSONResult.success();
    }

    //批量从ES中删除课程数据
    @PostMapping("/deleteBatchCourseFromEs2")
    public JSONResult deleteBatchCourseFromEs2(@RequestBody List<Long> docIds){
        //将数据存入ES中
        for(int i=0; i<docIds.size(); i++){
            repo.deleteById(docIds.get(i));
        }
        return JSONResult.success();
    }
}